package com.ebai.product.management.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ebai.product.management.base.controller.WebController;
import com.ebai.product.management.base.utils.Common;
import com.ebai.product.management.model.entity.User;

@Controller
public class LoginController extends WebController {

    @Value("${system.title}")
    private String systemTitle;

    @RequestMapping("/login")
    public String login(ModelMap modelMap) {
        modelMap.addAttribute("page_title", systemTitle);
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(ModelMap modelMap, HttpSession session) {
    	try {
			//退出
//    		session.invalidate();
			SecurityUtils.getSubject().logout();
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
        
        return "redirect:/login";
    }

    /**
     * AJAX登录异步校验
     * @param session 会话
     * @param response HTTP响应
     * @param user 登录用户
     */
    @RequestMapping("/ajaxChkLogin")
    public void ajaxChkLogin(HttpSession session, HttpServletResponse response, User user) {
//        JSONObject json = Common.getJsonResult(this.basicSecurityManager.chkLogin(session, user));
        UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(), user.getLoginPasswd(), false);
        Subject subject = SecurityUtils.getSubject();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("success", false);
        
        try {
            subject.login(token);
            map.put("success", true);
        }
        catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            map.put("data", msg);
        }
        this.sendDirectToClient(response, CONTENTTYPE_JSON, Common.getJsonResult(map).toString());
    }
}
